package com.robot.admin.config;

import com.robot.admin.dao.AdminDao;
import com.robot.admin.pojo.Admin;
import com.robot.admin.pojo.Privilege;
import com.robot.admin.pojo.Roles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义获取登录时获取用户数据
 * @author william
 */
@Service("userDetailsService")
@Transactional
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminDao adminDao;

    public MyUserDetailsServiceImpl() {
        super();
    }

    @Override
    public UserDetails loadUserByUsername(final String phone) throws UsernameNotFoundException {

        /**
         * 通过phone获取管理员信息
         * 返回user给security进行验证
         */
        try {
            final Admin admin = adminDao.findAdminByPhone(phone);
            if (admin == null) {
                throw new UsernameNotFoundException("No admin found with username: " + phone);
            }

            return new org.springframework.security.core.userdetails.User(admin.getPhone(),
                                                                            admin.getPassword(),
                                                                            getAuthorities(admin.getRoles()));
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 进行角色授权
     * @param roles
     * @return
     */
    private final Collection<? extends GrantedAuthority> getAuthorities(final Collection<Roles> roles) {
        return getGrantedAuthorities(getPrivileges(roles));
    }


    private final List<String> getPrivileges(final Collection<Roles> roles) {
        final List<String> privileges = new ArrayList<>();
        final List<Privilege> collection = new ArrayList<>();
        for (final Roles role : roles) {
            collection.addAll(role.getPrivileges());
        }
        for (final Privilege item : collection) {
            privileges.add(item.getName());
        }

        return privileges;
    }

    private final List<GrantedAuthority> getGrantedAuthorities(final List<String> privileges) {
        final List<GrantedAuthority> authorities = new ArrayList<>();
        for (final String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }
        return authorities;
    }
    

}
